package com.lt.flashcard.view;

import java.util.List;

import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zul.event.PagingEvent;

import com.lt.flashcard.Utility;
import com.lt.flashcard.model.entity.ProductCode;
import com.lt.flashcard.model.entity.User;
import com.lt.flashcard.model.service.AAService;
import com.lt.flashcard.model.service.EcommerceService;
import com.lt.flashcard.model.service.Repository;

public class AdminCodeVm {

	private int curpage = 0;
	private int pagesize = 40;
	private long total = 0;
	private String txtCode = "";
	
	private List<ProductCode> codes;
	
	private User user;
	
	@Init
	public void init() {
		AAService srv  = Repository.getInstance().getAAService();
		if(!srv.isLogin() || !srv.hasRole("admin")) {
			Utility.redirect("/admin_login.zul", false);
			return;
		}
		
		user = srv.getCurrentUser();
		loadCodeList();
		countTotal();
	}
	
	@NotifyChange("codes")
	@Command
	public void paging(@BindingParam("event") PagingEvent event) {
		curpage = event.getActivePage();
		loadCodeList();
	}
	
	@Command
	public void search() {
		if(Utility.isEmptyString(txtCode))
			return;
		
		
	}
	
	/**
	 * Load code list from database
	 */
	private void loadCodeList() {
		EcommerceService srv = Repository.getInstance().getEcommerceService();
		codes = srv.getProductCodes(curpage, pagesize);
	}
	
	private void countTotal() {
		EcommerceService srv = Repository.getInstance().getEcommerceService();
		total = srv.countProductCodes();
	}
	
	public User getUser(){
		return user;
	}
	
	public void setUser(User user){
		this.user = user;
	}

	/**
	 * @return the pagesize
	 */
	public int getPagesize() {
		return pagesize;
	}

	/**
	 * @param pagesize the pagesize to set
	 */
	public void setPagesize(int pagesize) {
		this.pagesize = pagesize;
	}

	/**
	 * @return the curpage
	 */
	public int getCurpage() {
		return curpage;
	}

	/**
	 * @param curpage the curpage to set
	 */
	public void setCurpage(int curpage) {
		this.curpage = curpage;
	}

	/**
	 * @return the total
	 */
	public long getTotal() {
		return total;
	}

	/**
	 * @param total the total to set
	 */
	public void setTotal(long total) {
		this.total = total;
	}
	
	/**
	 * @return the codes
	 */
	public List<ProductCode> getCodes() {
		return codes;
	}

	/**
	 * @param codes the codes to set
	 */
	public void setCodes(List<ProductCode> codes) {
		this.codes = codes;
	}

	/**
	 * @return the txtCode
	 */
	public String getTxtCode() {
		return txtCode;
	}

	/**
	 * @param txtCode the txtCode to set
	 */
	public void setTxtCode(String txtCode) {
		this.txtCode = txtCode;
	}
}
